package com.vermouth.filter;

import com.bachongLightNovel.constant.RedisConstant;
import com.bachongLightNovel.error.ErrorCodeEnum;
import com.bachongLightNovel.exception.CustomException;
import com.bachongLightNovel.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 登录超时过滤器
 * @author vermouth
 */
@Component
@Slf4j
public class TimeoutFilter implements GlobalFilter , Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("验证登录是否过期。。。");
        //放过登录请求
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        if (request.getPath().toString().contains("login") ||request.getPath().toString().contains("userinfo")){
            return chain.filter(exchange);
        }
        //放过注册接口
        if (request.getURI().getPath().contains("register")){
            return chain.filter(exchange);
        }
        //放过文件上传接口
        if (request.getURI().getPath().contains("upload")){
            return chain.filter(exchange);
        }
        //其他情求，判断redis是否过期
        //先获取token
        String token = request.getHeaders().getFirst("Token");
        Claims claims = JwtUtils.parseJWT(token);
        //获取用户名
        Object username = claims.get("username");
        //判断是否过期
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(RedisConstant.BACHONG_LOGIN_TOKEN + username))) {
            response.setRawStatusCode(513);
//            throw new CustomException(ErrorCodeEnum.LOGIN_TIMEOUT);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
